<template>
  <div class="app-container">
    <!--工具栏-->
    <el-tabs v-model="appType" style="margin-bottom: 0;" @tab-click="handleTabChange">
      <el-tab-pane v-for="item in appTypes" :key="'app'+item.value" :label="item.title" :name="item.value" />
    </el-tabs>
    <div class="head-container">
      <div v-show="crud.props.searchToggle" class="top-box">
        <el-input
          v-model="query.blurry"
          clearable
          prefix-icon="el-icon-search"
          size="small"
          placeholder="输入标题搜索"
          style="width: 340px;"
          @keyup.enter.native="crud.toQuery"
        />
        <el-date-picker
          v-model="query.startTime"
          style="width: 190px"
          type="datetime"
          placeholder="选择开始时间"
          align="right"
          :picker-options="pickerOptions"
          :value-format="dateFormat"
          @change="handleTimeChange(true)"
        />
        <span style="font-size: 12px; padding: 0 2px; vertical-align: middle">~</span>
        <el-date-picker
          v-model="query.endTime"
          style="width: 190px"
          type="datetime"
          placeholder="选择结束时间"
          align="right"
          :picker-options="pickerOptions"
          :value-format="dateFormat"
          @change="handleTimeChange(false)"
        />
        <rrOperation :crud="crud" />
      </div>
      <!--如果想在工具栏加入更多按钮，可以使用插槽方式， slot = 'left' or 'right'-->
      <crudOperation :permission="permission">
        <el-button
          slot="right"
          v-permission="permission.import"
          :loading="crud.downloadLoading"
          class="filter-item"
          type="primary"
          size="mini"
          icon="el-icon-download"
          @click="downLoadTemplate"
        >下载模板</el-button>
        <!-- 导入 -->
        <el-upload
          ref="upload"
          slot="right"
          v-permission="permission.import"
          :limit="1"
          accept=".xlsx"
          :auto-upload="true"
          :action="actionUrl"
          :headers="headers"
          :before-upload="handleBeforeUpload"
          :data="actionData"
          :on-success="handleSuccess"
          :on-error="handleError"
          style="display: inline-block"
          :show-file-list="false"
        >
          <el-button class="filter-item" type="primary" size="mini" icon="el-icon-upload" :loading="isImporting">导入</el-button>
        </el-upload>
      </crudOperation>
      <!--表单组件-->
      <el-dialog :close-on-click-modal="false" :before-close="crud.cancelCU" :visible.sync="crud.status.cu > 0" :title="crud.status.title" width="540px">
        <el-form ref="form" :model="form" :rules="rules" size="small" label-width="120px">

          <!-- <el-form-item prop="appType"  label="系统">
            <el-input  :defaultValue="'工场'" disabled style="width: 370px;" />
          </el-form-item>-->
          <el-form-item label="应用名称" prop="appName">
            <span>{{ form.appName }}</span>
          </el-form-item>

          <el-form-item label="菜单标题" prop="appRouteName">
            <el-autocomplete
              v-if="appType<5"
              v-model="form.appRouteName"
              class="inline-input"
              :fetch-suggestions="querySearch"
              placeholder="请输入菜单标题"
              style="width: 370px;"
              :maxlength="100"
              @select="handleSelectRouteName"
            />
            <el-input
              v-else
              v-model="form.appRouteName"
            />
          </el-form-item>
          <el-form-item label="菜单路由" prop="appRoute">
            <el-input v-model="form.appRoute" style="width: 370px;" />
          </el-form-item>
          <el-form-item label="地址参数" prop="appParam">
            <div slot="label">地址参数
              <el-tooltip content="参数以键值对形式(如：name=model)，多个参数以'&'隔开（如:subNo=01&name=model）" effect="dark" placement="bottom">
                <svg-icon icon-class="help" class="navSvgSty" />
              </el-tooltip>
            </div>
            <el-input v-model="form.appParam" style="width: 370px;" />
          </el-form-item>
          <el-form-item label="handbook链接" prop="bookUrl">
            <el-input v-model="form.bookUrl" style="width: 370px;" />
          </el-form-item>

          <!--<el-form-item label="章节" prop="chapter">
            <el-input v-model="form.chapter" style="width: 370px;" :maxlength="50" />
          </el-form-item>-->
          <el-form-item label="标题" prop="title">
            <el-input v-model="form.title" style="width: 370px;" :maxlength="100" />
          </el-form-item>
          <el-form-item label="权重" prop="weight">
            <el-input-number v-model="form.weight" controls-position="right" :min="0" :step="1" :precision="0" :max="9999" />
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button @click="crud.cancelCU">取消</el-button>
          <el-button :loading="crud.status.cu === 2" type="primary" @click="crud.submitCU">确认</el-button>
        </div>
      </el-dialog>
      <!--表格渲染-->
      <el-table ref="table" v-loading="crud.loading" stripe height="calc(100vh - 360px)" :data="crud.data" size="small" style="width: 100%;" @selection-change="crud.selectionChangeHandler">
        <el-table-column type="selection" width="55" />
        <el-table-column prop="appName" label="应用名称" />
        <el-table-column prop="appRouteName" label="菜单标题" show-overflow-tooltip />
        <el-table-column prop="appRoute" label="菜单路由" />
        <el-table-column prop="appParam" label="地址参数" />
        <el-table-column prop="bookUrl" label="handbook的链接" min-width="200">
          <template slot-scope="scope">
            <div><el-link :href="scope.row.bookUrl" type="primary" target="_blank">{{ scope.row.bookUrl }}</el-link></div>
          </template>
        </el-table-column>
        <el-table-column prop="title" label="标题" min-width="140" show-overflow-tooltip />
        <el-table-column prop="weight" label="权重" width="80" />
        <el-table-column prop="createBy" label="创建者" />
        <el-table-column prop="updateBy" label="更新者" />
        <el-table-column prop="createTime" label="创建日期" />
        <el-table-column prop="updateTime" label="更新时间" />
        <el-table-column v-if="checkPer(['admin','helpDoc:edit','helpDoc:del'])" label="操作" width="150px" align="center">
          <template slot-scope="scope">
            <udOperation
              :data="scope.row"
              :permission="permission"
            />
          </template>
        </el-table-column>
      </el-table>
      <!--分页组件-->
      <pagination />
    </div>
  </div>
</template>

<script>
import crudManualDescription, { getMenus } from '@/api/system/manualDescription'
import CRUD, { presenter, header, form, crud } from '@brotherCrud/crud'
import rrOperation from '@brotherCrud/RR.operation'
import crudOperation from '@brotherCrud/CRUD.operation'
import udOperation from '@brotherCrud/UD.operation'
import pagination from '@brotherCrud/Pagination'
import { download } from '@/api/data'
import { downloadFile } from '@/utils'
import { getToken } from '@/utils/auth'
import { appTypes as _appTypes } from '@haisum-cloud/ui-components/packages/utils'
const appTypes = [...Object.values(_appTypes)].sort((a, b) => a.value - b.value)
const defaultForm = { appType: null, appName: null, appRouteName: null, appRoute: null, appParam: '', bookUrl: null, chapter: null, title: null, weight: null }
export default {
  name: 'ManualDescription',
  components: { pagination, crudOperation, rrOperation, udOperation },
  mixins: [presenter(), header(), form(defaultForm), crud()],
  cruds() {
    return CRUD({ title: '帮助文档条目', url: 'api/manualDescription', idField: 'id', sort: 'id,desc', crudMethod: { ...crudManualDescription },
      optShow: {
        add: true,
        edit: true,
        del: true,
        reset: true,
        download: false
      }
    }
    )
  },
  data() {
    const validateURL = (rule, value, callback) => {
      if (value && value.match(/^(https?:\/\/)((([0-9]{1,3}\.){3}[0-9]{1,3})|(([a-zA-Z0-9-]+\.)+[a-zA-Z]{2,}))(:[0-9]{1,5})?(\/[^\s]*)?$/)) {
        callback()
      } else {
        callback(new Error('请输入合法的URL链接'))
      }
    }

    const validateQueryParams = (rule, value, callback) => {
      if (value === '') callback()
      const regex = /^([^&=]+)=([^&=]+)(?:&([^&=]+)=([^&=]+))*$/
      if (regex.test(value)) {
        callback()
      } else {
        callback(new Error('格式错误，正确格式："name=model"或"subNo=01&name=model"'))
      }
    }

    return {
      appType: '1',
      appTypes: [...appTypes],
      appTypesMap: appTypes.reduce((prev, current) => {
        prev[current.value] = { ...current }
        return prev
      }, {}),
      routeData: [],
      menus: {},
      permission: {
        add: ['admin', 'helpDoc:add'],
        edit: ['admin', 'helpDoc:edit'],
        del: ['admin', 'helpDoc:del'],
        import: ['admin', 'helpDoc:import']
      },
      rules: {
        appRouteName: [
          { required: true, message: '菜单标题不能为空', trigger: 'change' }
        ],
        appRoute: [
          { required: true, message: '菜单路由不能为空', trigger: 'change' }
        ],
        appParam: [
          { validator: validateQueryParams, trigger: 'blur' }
        ],
        bookUrl: [
          { required: true, message: 'handbook的链接不能为空', trigger: 'change' },
          { validator: validateURL, trigger: 'blur' }
        ],
        title: [
          { required: true, message: 'handbook文章标题不能为空', trigger: 'change' }
        ]
      },
      dateFormat: 'yyyy-MM-dd HH:mm:ss',
      pickerOptions: {
        shortcuts: [{
          text: '今天',
          onClick(picker) {
            picker.$emit('pick', new Date())
          }
        }, {
          text: '昨天',
          onClick(picker) {
            const date = new Date()
            date.setTime(date.getTime() - 3600 * 1000 * 24)
            picker.$emit('pick', date)
          }
        }, {
          text: '一周前',
          onClick(picker) {
            const date = new Date()
            date.setTime(date.getTime() - 3600 * 1000 * 24 * 7)
            picker.$emit('pick', date)
          }
        }]
      },
      headers: {
        Authorization: getToken()
      },
      isImporting: false
    }
  },
  computed: {
    actionData() {
      return {
        appType: this.currentType?.value,
        appName: this.currentType?.title
      }
    },
    currentType() {
      return this.appTypesMap[this.appType]
    },
    actionUrl() {
      return process.env.VUE_APP_BASE_API + `/api/manualDescription/importData`
    }
  },
  created() {
    this.getMenus()
  },
  methods: {
    // 钩子：在获取表格数据之前执行，false 则代表不获取数据
    [CRUD.HOOK.beforeRefresh]() {
      this.query.appType = this.appType
      return true
    },
    [CRUD.HOOK.beforeToAdd](crud, form) {
      const defaultKeys = Object.keys(defaultForm)
      Object.keys(this.form).forEach(key => {
        if (!defaultKeys.includes(key)) {
          delete this.crud.form[key]
        }
      })
      this.form.appName = this.currentType.title
      this.form.appType = this.currentType.value
    },
    getMenus() {
      if (this.menus[this.appType]) return
      getMenus({
        appType: this.appType,
        type: 1
      }).then(res => {
        this.$set(this.menus, this.appType, res)
      })
    },
    handleTabChange() {
      this.getMenus()
      this.crud.toQuery()
    },
    handleSelectRouteName(item) {
      this.form.appRoute = item.path
    },
    querySearch(queryString, cb) {
      if (this.appType > 4) cb([])
      const menus = this.menus[this.appType] || []
      const results = queryString ? menus.filter(item => { return item.title.toLowerCase().indexOf(queryString.toLowerCase()) >= 0 }) : menus
      // 调用 callback 返回建议列表的数据
      results.forEach(item => {
        item.value = item.title
      })
      cb(results)
    },
    handleTimeChange(isStartDate) {
      if (isStartDate && this.query.startTime && this.query.endTime) {
        if (new Date(this.query.startTime).getTime() > new Date(this.query.endTime).getTime()) {
          this.$message.error('开始时间不得大于结束时间')
          this.query.startTime = ''
        }
      } else if (!isStartDate && this.query.startTime && this.query.endTime) {
        if (new Date(this.query.startTime).getTime() > new Date(this.query.endTime).getTime()) {
          this.$message.error('结束时间不得小于开始时间')
          this.query.endTime = ''
        }
      }
      this.crud.toQuery()
    },
    // 导出
    downLoadTemplate() {
      this.crud.downloadLoading = true
      download('api/manualDescription/downloadTemplate').then(result => {
        downloadFile(result, '云工场手册说明导入模板', 'xlsx', false)
        this.crud.downloadLoading = false
      }).catch(() => {
        this.crud.downloadLoading = false
      })
    },
    handleBeforeUpload() {
      this.isImporting = true
      return true
    },

    handleSuccess() {
      this.$refs.upload.clearFiles()
      this.crud.toQuery()
      this.isImporting = false
      this.$notify({
        title: '导入成功',
        type: 'success',
        duration: 2500
      })
    },
    handleError(e, file, fileList) {
      this.$refs.upload.clearFiles()
      const msg = JSON.parse(e.message)
      this.isImporting = false
      this.$notify({
        title: msg.message,
        type: 'error',
        duration: 2500
      })
    }
  }
}
</script>

  <style scoped lang="scss">
    .top-box{
      ::v-deep .filter-item{
       margin: 0 4px;
      }
    }
  </style>
